<?php declare(strict_types=1);

/**
 * @author      guosir
 * @copyright   2023-2025 owner
 **/

namespace Srv\Apps\Apis\Promotion\Ctl;

use Srv\Apps\Apis\Common\Ctl\DevicePushCtl;
use Srv\Apps\Apis\Common\DefCtl\DefChannelCtl;
use Srv\Apps\Apis\Common\DefCtl\DefDeviceLangCtl;
use Srv\Apps\Apis\Common\DefCtl\DefDeviceModelCtl;
use Srv\Apps\Apis\Common\DefCtl\DefDeviceOsCtl;
use Srv\Apps\Apis\Common\DefCtl\DefPlatformCtl;
use Srv\Apps\Apis\Common\IdxCtl\IdxIp;
use Srv\Apps\Apis\Skit\Ctl\SkitInfoCtl;
use Srv\Apps\Apis\User\Ctl\UserCtl;
use Srv\Apps\Proto\DTO\Promotion\WappRequestListDTO;
use Srv\Apps\Proto\VO\Promotion\WappRequestListVO;
use Srv\Apps\Proto\VO\Promotion\WappRequestVO;
use Srv\Apps\Proto\VO\Skit\SkitInfoVO;
use Srv\Apps\Proto\VO\User\UserInfoBasicVO;
use Srv\Libs\Common\CommArray;
use Srv\Libs\Frame\ControllerAbstract;
use Srv\Libs\Frame\Page;
use Srv\Libs\Storage\DataMysql;
use Srv\Libs\Tools\IpAddr;

final class WappRequestCtl extends ControllerAbstract
{
    private ?DataMysql $DbAuto              = null;     // DB-Write



    /**
     * @return static
     * tag
     */
    final public static function tag():self
    {
        $thisObject                         = self::tagGet();
        if($thisObject instanceof self){
            $thisObject->DbAuto             = self::getDbAuto();
        }
        return $thisObject;
    }

    /**
     * @param int $warrId
     * @return array
     * getWappRequestSrc
     */
    public function getWappRequestSrc(int $warrId):array
    {
        if($warrId < 1) return [];
        $isFail     = false;
        $info       = $this->DbAuto->getDataOne('SELECT warr_id, walr_id, skio_id, warr_uuid, warr_ip, dcht_id, ua_id, ddpt_id, ddlt_id, ddot_id, ddmt_id, warr_width, warr_height, wifb_id, wimd_id, wise_id, wiui_id, wict_id, witm_id, wicn_id, dup_id_match, warr_match_time, warr_create_day_time, warr_create_time FROM '.$this->DbAuto->getTableNameAll('wapp_request_record').' WHERE warr_id='.$warrId, $isFail);
        if($isFail || !isset($info['warr_id'])) return [];
        return $info;
    }

    /**
     * @param Page $Page
     * @param array $whereData
     * @return WappRequestListVO|null
     * getWappRequestList
     */
    public function getWappRequestList(Page $Page, array $whereData): ?WappRequestListVO
    {
        $limitString            = $Page->getLimitString();
        $whereString            = ' WHERE 1 ';
        // 检索条件
        if(count($whereData) > 0)foreach ($whereData as $key => $val){
            switch ($key){
                case WappRequestListDTO::_warrId:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'warr_id='. intval($val);
                    break;
                case WappRequestListDTO::_walrId:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'walr_id='. intval($val);
                    break;
                case WappRequestListDTO::_skioId:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'skio_id='. intval($val);
                    break;
                case WappRequestListDTO::_createDayTime:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'warr_create_day_time='. intval($val);
                    break;
                case WappRequestListDTO::_uuid:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'warr_uuid=\''.$this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case WappRequestListDTO::_putChannel:
                    if($val === '1'){
                        $whereString    .= (strlen($whereString)>0?' AND ':'').'LENGTH(warr_chnl)>0';
                    }else{
                        $whereString    .= (strlen($whereString)>0?' AND ':'').'warr_chnl LIKE \''.$this->DbAuto->getRealEscapeString($val).'%\'';
                    }
                    break;
                case WappRequestListDTO::_pixelId:
                    if($val === '1'){
                        $whereString    .= (strlen($whereString)>0?' AND ':'').'LENGTH(warr_pixel_id)>0';
                    }else{
                        $whereString    .= (strlen($whereString)>0?' AND ':'').'warr_pixel_id LIKE \''.$this->DbAuto->getRealEscapeString($val).'%\'';
                    }
                    break;
                case WappRequestListDTO::_createTimeStart:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'warr_create_time>='. intval($val);
                    break;
                case WappRequestListDTO::_createTimeStop:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'warr_create_time<='. intval($val);
                    break;
            }
        }
        $isFail                 = false;
        $sql                    = 'SELECT SQL_CALC_FOUND_ROWS warr_id, walr_id, skio_id, warr_uuid, warr_pixel_id, warr_chnl, warr_ip, dcht_id, ua_id, ddpt_id, ddlt_id, ddot_id, ddmt_id, warr_width, warr_height, wifb_id, wimd_id, wise_id, wiui_id, wict_id, witm_id, wicn_id, dup_id_match, warr_match_time, warr_create_day_time, warr_create_time FROM '.$this->DbAuto->getTableNameAll('wapp_request_record').$whereString.' ORDER BY warr_id DESC '.$limitString;
        $list                   = $this->DbAuto->getData($sql, $isFail);
        $totalNum               = $this->DbAuto->getDataInt('SELECT FOUND_ROWS() as num', 'num');
        if($isFail) return null;
        $WappRequestVOList      = [];
        if(CommArray::isForeach($list)){
            $DevicePushCtl      = DevicePushCtl::tag();
            $DefPlatformCtl     = DefPlatformCtl::tag();
            $DefDeviceLangCtl   = DefDeviceLangCtl::tag();
            $DefDeviceOsCtl     = DefDeviceOsCtl::tag();
            $DefDeviceModelCtl  = DefDeviceModelCtl::tag();
            $UserCtl            = UserCtl::tag();
            $skioIdList         = array_map('intval', array_unique(array_column($list, 'skio_id')));
            $SkitInfoVOList     = SkitInfoCtl::tag()->getSkitInfoBatch($skioIdList);
            $uaIdList           = array_map('intval', array_unique(array_column($list, 'ua_id')));
            $uaSrcList          = $DevicePushCtl->getUaByIdBatch($uaIdList);
            $ddptIdList         = array_map('intval', array_unique(array_column($list, 'ddpt_id')));
            $devicePlatformList = $DefPlatformCtl->getExtStrByIdBatch($ddptIdList, $DefPlatformCtl::EXT_NAME);
            $ddltIdList         = array_map('intval', array_unique(array_column($list, 'ddlt_id')));
            $deviceLangList     = $DefDeviceLangCtl->getExtStrByIdBatch($ddltIdList, $DefDeviceLangCtl::EXT_NAME);
            $ddotIdList         = array_map('intval', array_unique(array_column($list, 'ddot_id')));
            $deviceOsList       = $DefDeviceOsCtl->getExtStrByIdBatch($ddotIdList, $DefDeviceOsCtl::EXT_NAME);
            $ddmtIdList         = array_map('intval', array_unique(array_column($list, 'ddmt_id')));
            $deviceModeList     = $DefDeviceModelCtl->getExtStrByIdBatch($ddmtIdList, $DefDeviceModelCtl::EXT_NAME);
            $dupIdMatchList     = array_map('intval', array_unique(array_column($list, 'dup_id_match')));
            $devicePushSrcList  = $DevicePushCtl->getDevicePushUserSrcBatch($dupIdMatchList);
            foreach($list as $info){
                $warrIdItem             = intval($info['warr_id']??0);
                if($warrIdItem < 1) continue;
                $WappRequestVO          = $this->getWappRequestVO($info);
                if(!($WappRequestVO instanceof WappRequestVO)) continue;
                $skioIdItem             = intval($info['skio_id']);
                $SkitInfoVO             = $SkitInfoVOList[$skioIdItem]??null;
                if($SkitInfoVO instanceof SkitInfoVO) {
                    $WappRequestVO->setSkitInfo($SkitInfoVO);
                }
                $WappRequestVO->setUa($uaSrcList[intval($info['ua_id'])]??'');
                $WappRequestVO->setPlatform($devicePlatformList[intval($info['ddpt_id'])]??'');
                $WappRequestVO->setDeviceLang($deviceLangList[intval($info['ddlt_id'])]??'');
                $WappRequestVO->setDeviceOs($deviceOsList[intval($info['ddot_id'])]??'');
                $WappRequestVO->setDeviceMode($deviceModeList[intval($info['ddmt_id'])]??'');
                if($WappRequestVO->getDupIdMatch() > 0){
                    $userIdFirst        = intval($devicePushSrcList[$WappRequestVO->getDupIdMatch()]['user_id_first']);
                    $UserInfoBasicVO    = $UserCtl->getUserInfoBasicOne($userIdFirst);
                    if($UserInfoBasicVO instanceof UserInfoBasicVO) $WappRequestVO->setUserInfoBasicMatch($UserInfoBasicVO);
                }
                $WappRequestVOList[]    = $WappRequestVO;
            }
        }
        $WappRequestListVO              = new WappRequestListVO();
        $WappRequestListVO->setList($WappRequestVOList);
        $WappRequestListVO->setPage($Page->getPageVO($totalNum));
        return $WappRequestListVO;
    }

    /**
     * @param int $warrId
     * @return WappRequestVO|null
     * getWappRequestInfo
     */
    public function getWappRequestInfo(int $warrId):?WappRequestVO
    {
        $infoSrc    = $this->getWappRequestSrc($warrId);
        if(!isset($infoSrc['warr_id'])) return null;
        return $this->getWappRequestVO($infoSrc);
    }

    /**
     * @param array $info
     * @return WappRequestVO|null
     * getWappRequestVO
     */
    public function getWappRequestVO(array $info):?WappRequestVO
    {
        $warrId             = intval($info['warr_id']??0);
        if($warrId < 1) return null;
        $WappRequestVO      = new WappRequestVO();
        $WappRequestVO->setWarrId($warrId);
        $WappRequestVO->setWalrId(intval($info['walr_id']));
        $WappRequestVO->setSkioId(intval($info['skio_id']));
        $WappRequestVO->setUuid(trim($info['warr_uuid']));
        $WappRequestVO->setPixelId(trim($info['warr_pixel_id']));
        $WappRequestVO->setPutChannel(trim($info['warr_chnl']));
        $ipStr              = IdxIp::tag()->getIpStrByIntStr($info['warr_ip']);
        $ipArea             = IpAddr::getLocationInfo($ipStr);
        $WappRequestVO->setIpStr($ipStr.'('.($ipArea['country']??'-').')');
        $dchtId             = intval($info['dcht_id']);
        if($dchtId > 0){
            $channel        = DefChannelCtl::tag()->getExtStrById($dchtId, DefChannelCtl::EXT_NAME);
            $WappRequestVO->setChannel($channel);
        }
        $WappRequestVO->setDeviceWidth(intval($info['warr_width']));
        $WappRequestVO->setDeviceHeight(intval($info['warr_height']));
        $WappRequestVO->setDupIdMatch(intval($info['dup_id_match']));
        $WappRequestVO->setMatchTime(intval($info['warr_match_time']));
        $WappRequestVO->setCreateDayTime(intval($info['warr_create_day_time']));
        $WappRequestVO->setCreateTime(intval($info['warr_create_time']));
        return $WappRequestVO;
    }
}